package com.tgpms.web.tongfei;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tgpms.common.Result;
import com.tgpms.web.tongfei.pojo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Api(value = "TongfeiController", tags = "同飞系统相关接口")
@RequestMapping("/tongfei")
public class TongfeiController implements InitializingBean {
    @Value("${tongfei.path}")
    private String host;
    public static String HOST;
    @Resource
    private RedisTemplate<String, Object> redis;

    private String generateCode = "/auth/generateCode"; // 获取验证码图片
    private String loginPath = "/auth/oauth/login"; // 登录
    private String logout = "/auth/token/"; // 退出

    /**
     * 获取验证码图片
     */
    @ApiOperation(value = "获取验证码图片", notes = "获取验证码图片", httpMethod = "GET")
    @GetMapping("/auth/generateCode")
    public Result generateCode() {
        String body = HttpRequest.get(HOST + generateCode)
                .execute().body();
        return tongfeiResponseToResult(JSON.parseObject(body, R.class));
    }

    /**
     * 登录
     */
    @ApiOperation(value = "同飞登录", notes = "同飞登录", httpMethod = "POST")
    @PostMapping("/auth/oauth/login")
    public Result login(String username, String password, String code, String codeid) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("username", username);
        paramMap.put("password", password);
        String result = HttpRequest.post(host + loginPath)
                .header(Header.CONTENT_TYPE.toString(), "application/x-www-form-urlencoded")
                .header("code", code)
                .header("codeid", codeid)
                .form(paramMap)
                .execute().body();
        Result result1 = tongfeiResponseToResult(JSON.parseObject(result, R.class));
        if (result1.getSuccess()) {
            // token和用户名存redis
            String json = JSON.toJSONString(result1.getData());
            JSONObject jsonObject = JSON.parseObject(json);
            String accessToken = (String) jsonObject.get("accessToken");
            redis.opsForValue().set(accessToken, username, 2, TimeUnit.HOURS);
        }
        return result1;
    }

    /**
     * 退出
     */
    @ApiOperation(value = "同飞退出", notes = "同飞退出", httpMethod = "POST")
    @PostMapping("/auth/token/{token}")
    public Result logout(@PathVariable("token") String token) {
        String result = HttpRequest.delete(host + logout + token)
                .header(Header.AUTHORIZATION, "Bearer " + token)
                .execute().body();
        Result result1 = tongfeiResponseToResult(JSON.parseObject(result, R.class));
        if (result1.getSuccess()) {
            redis.delete(token);
        }
        return result1;
    }

    /**
     * 查询当前用户性质
     */
    @ApiOperation(value = "查询当前用户性质", notes = "查询当前用户性质", httpMethod = "GET")
    @GetMapping("/base/user/user/userType")
    public Result userType(HttpServletRequest request) {
        String token = request.getHeader("tfToken");
        String body = HttpRequest.get(HOST + "/base/user/user/userType")
                .header(Header.AUTHORIZATION, "Bearer " + token)
                .execute().body();
        return tongfeiResponseToResult(JSON.parseObject(body, R.class));
    }


    /**
     * 通过key查询系统码表
     */
    @ApiOperation(value = "通过key查询系统码表", notes = "通过key查询系统码表", httpMethod = "GET")
    @GetMapping("/base/code/getByKeys")
    public Result getByKeys(@RequestParam("keys") String keys, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("keys", keys);
        return normalGet("/base/code/getByKeys", paramMap, request);
    }

    /**
     * 根据FTP文件地址获取图片
     */
    @ApiOperation(value = "根据FTP文件地址获取图片", notes = "根据FTP文件地址获取图片", httpMethod = "GET")
    @GetMapping("/base/file/loadImg")
    public Result loadImg(@RequestParam("remotePath") String remotePath, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("tfToken");
        String path = String.format("/base/file/loadImg?remotePath=%s&access_token=%s",remotePath,token);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(HOST + path);
        CloseableHttpResponse resp;
        try {
            resp = httpClient.execute(httpGet);// 调用服务器接口
            byte[] data = EntityUtils.toByteArray(resp.getEntity());// 将图片或者文件转化成数组的形式
//            OutputStream toClient = response.getOutputStream();// 获取输出流
//            toClient.write(data);// 将这个数组写入输出流中
//            toClient.close();
            BASE64Encoder encoder = new BASE64Encoder();
            String imageBase64 ="data:image/png;base64,"+ encoder.encode(data);
            imageBase64 = imageBase64.replaceAll("\r\n|\r|\n", "");// 替换換行和回车
            imageBase64 = imageBase64.replaceAll(" ","");
            return Result.OK(imageBase64);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        }
    }

    /**
     * 根据PBS编码查询固件信息和录入的管点信息
     */
    @ApiOperation(value = "根据PBS编码查询固件信息和录入的管点信息", notes = "根据PBS编码查询固件信息和录入的管点信息", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/structure/getPsNodeInfo")
    public Result getPsNodeInfo(@RequestParam("pbs") String pbs, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("pbs", pbs);
        return normalGet("/tofly-sxgk/structure/getPsNodeInfo", paramMap, request);
    }

    /**
     * 根据PBS编码查询固件信息和录入的管线信息
     */
    @ApiOperation(value = "根据PBS编码查询固件信息和录入的管线信息", notes = "根据PBS编码查询固件信息和录入的管线信息", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/structure/getPsPipeInfo")
    public Result getPsPipeInfo(@RequestParam("pbs") String pbs, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("pbs", pbs);
        return normalGet("/tofly-sxgk/structure/getPsPipeInfo", paramMap, request);
    }

    /**
     * 获取用户绑定道路列表
     */
    @ApiOperation(value = "查询用户所属街道的全部固件信息", notes = "查询用户所属街道的全部固件信息", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/structure/findUserPsInfo")
    public Result findUserPsInfo(HttpServletRequest request) {
        return normalGet("/tofly-sxgk/structure/findUserPsInfo", null, request);
    }

    /**
     * 获取用户绑定道路列表
     */
    @ApiOperation(value = "获取用户绑定道路列表", notes = "获取用户绑定道路列表", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/useroad/listRoads")
    public Result listRoads(HttpServletRequest request) {
        return normalGet("/tofly-sxgk/useroad/listRoads", null, request);
    }

    /**
     * 管点查看PBS二维码图片
     */
    @ApiOperation(value = "管点查看PBS二维码图片", notes = "管点查看PBS二维码图片", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/structure/createPicNode")
    public Result createPicNode(@RequestParam("pbs") String pbs, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("tfToken");
        String path = String.format("/tofly-sxgk/structure/createPicNode?pbs=%s&access_token=%s",pbs,token);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(HOST + path);
        CloseableHttpResponse resp;
        try {
            resp = httpClient.execute(httpGet);// 调用服务器接口
            byte[] data = EntityUtils.toByteArray(resp.getEntity());// 将图片或者文件转化成数组的形式
//            OutputStream toClient = response.getOutputStream();// 获取输出流
//            toClient.write(data);// 将这个数组写入输出流中
//            toClient.close();
            BASE64Encoder encoder = new BASE64Encoder();
            String imageBase64 ="data:image/png;base64,"+ encoder.encode(data);
            return Result.OK(imageBase64);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        }
    }

    /**
     * 管道查看PBS二维码图片
     */
    @ApiOperation(value = "管道查看PBS二维码图片", notes = "管道查看PBS二维码图片", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/structure/createPicPipe")
    public Result createPicPipe(@RequestParam("pbs") String pbs, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("tfToken");
        String path = String.format("/tofly-sxgk/structure/createPicPipe?pbs=%s&access_token=%s",pbs,token);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(HOST + path);
        CloseableHttpResponse resp;
        try {
            resp = httpClient.execute(httpGet);// 调用服务器接口
            byte[] data = EntityUtils.toByteArray(resp.getEntity());// 将图片或者文件转化成数组的形式
//            OutputStream toClient = response.getOutputStream();// 获取输出流
//            toClient.write(data);// 将这个数组写入输出流中
//            toClient.close();
            BASE64Encoder encoder = new BASE64Encoder();
            String imageBase64 ="data:image/png;base64,"+ encoder.encode(data);
            return Result.OK(imageBase64);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        }
    }

    public static Result tongfeiResponseToResult(R r) {
        Result result = new Result();
        result.setMsg(r.getMessage());
        result.setData(r.getResult());
        result.setSuccess(r.getCode() == 1);
        return result;
    }

    /**
     * 通用get请求访问同飞
     */
    public static Result normalGet(String path, Map<String, Object> paramMap, HttpServletRequest request) {
        String token = request.getHeader("tfToken");
        String body = HttpRequest.get(HOST + path)
                .header(Header.AUTHORIZATION, "Bearer " + token)
                .form(paramMap)
                .execute().body();
        return tongfeiResponseToResult(JSON.parseObject(body, R.class));
    }

    @Override
    public void afterPropertiesSet() {
        HOST = host;
    }
}
